const { app,nativeImage ,clipboard, MessageChannelMain,BrowserWindow ,screen ,Menu , Tray ,globalShortcut, ipcMain} = require('electron')
const path = require('node:path');
const fs = require("fs");
const robot = require("robotjs");
const auto = {
  keydown:(key) => {
    key.forEach((item) => {
      robot.keyToggle(item,"down")
    })
    setTimeout(()=>key.forEach((item) => {
      robot.keyToggle(item,"up")
      return true
    }),50)
  },
  click:(value = "left") => robot.mouseClick(value,false),
  dclick:(value = "left") => robot.mouseClick(value,true),
  move:(x,y) => robot.moveMouse(x,y),

  drag:(x1,y1,x2,y2) => {
    robot.moveMouse(x1,y1)
    robot.mouseToggle("down","left")
    robot.dragMouse(x2,y2)
    robot.mouseToggle("up","left")
  },
    keyTap:(key) => {
      key.forEach((item) => {robot.keyToggle(item,"down")})
      setTimeout(()=>key.forEach((item) => {robot.keyToggle(item,"up")}),50)
    },
    keyUp:(key) => robot.keyToggle(key,"up"),

}
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
  app.quit();
}
let mainID = null;
let settingID = null;
let infoID = null;
const createWindow = () => {
  // 主窗口
  const mainWindow = new BrowserWindow({
    width: 500,
    height: 500,
    frame: false,
    transparent: true,
    resizable: false,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      spellcheck: false,
      contextIsolation: true,
    },
  });
  // 编程窗口
  const codeWindow = new BrowserWindow({
    width: 1000,
    height: 500,
    frame: false,
    show: false,
    resizable: false,
    transparent: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      spellcheck: false
    },
  });

  const infoWindow = new BrowserWindow({
    width: 500,
    height: 300,
    frame: false,
    show: false,
    transparent: true,
    // resizable: false,
    // movable: false,
    alwaysOnTop: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      spellcheck: false
    },
  });
  let size = screen.getPrimaryDisplay().workAreaSize
  infoWindow.setPosition(size.width-infoWindow.getSize()[0],size.height-infoWindow.getSize()[1]+30);
  infoWindow.setFocusable(false)
  infoWindow.setIgnoreMouseEvents(true)


  mainID = mainWindow.id;
  settingID = codeWindow.id;
  infoID = infoWindow.id;

  ipcMain.on('set-info-resizeable', (event,ignore) => {
    const info = BrowserWindow.fromWebContents(event.sender)
    info.setIgnoreMouseEvents(!ignore)
    info.setResizable(ignore)
  })


  ipcMain.on('set-ignore-mouse-events', (event, ignore, options) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    win.setIgnoreMouseEvents(ignore, options)
  })


  ipcMain.on('setCodeHidden', (event,value) => {
    if (value){
      codeWindow.show()
    }else {
      codeWindow.hide()
    }
  })

  ipcMain.on('setInfoHidden', (event,value) => {
    if (value){
      infoWindow.show()
    }else {
      infoWindow.hide()
    }
  })

  ipcMain.on('click', (_,value) => {
    if(value === ""){
      value = "left"
    }
    auto.click(value)
  })

  ipcMain.on('dclick', (_,value) => {
    if(value === ""){
      value = "left"
    }
    auto.dclick(value)
  })

  ipcMain.on('move', (event,x,y) => {
    auto.move(x,y)
  })

  ipcMain.on('drag', (event,x1,y1,x2,y2) => {
    auto.drag(x1,y1,x2,y2)
  })

  ipcMain.on('keydown', (event,value) => {
    return auto.keydown([...value])
  })
  ipcMain.on('keyup', (event,value) => {
    return auto.keyUp([...value])
  })
  ipcMain.on('keytap', (event,value) => {
    return auto.keyTap([...value])
  })
  ipcMain.on('cv', (event,value) => {
    clipboard.writeText(value, 'selection')
    return auto.keydown(["control","v"])
  })

  ipcMain.on('sendTask', (event,value) => {
    BrowserWindow.fromId(infoID).webContents.send('task',value)
  })

  ipcMain.on('sendCode', (event,value) => {
    BrowserWindow.fromId(mainID).webContents.send('sendToAI',value)}
  )
  ipcMain.on('getCode', (event,value) => {
    BrowserWindow.fromId(mainID).webContents.send('onGetCode',value)}
  )
  ipcMain.on('sendCodes', (event,value) => {
    BrowserWindow.fromId(settingID).webContents.send('onGetCode',value)}
  )



  // and load the index.html of the app.
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL).then((r) => console.log("mainWindow loadURL",r));
    codeWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL+"/code").then((r) => console.log("codeWindow loadURL", r))
    infoWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL+"/info").then((r) => console.log("infoWindow loadURL", r))
  } else {
    mainWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`));
    codeWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),{hash:'code'});
    infoWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),{hash:'info'})
  }
};



// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(()=>{
      // Open the DevTools.
    globalShortcut.register('Alt+i', () => {
      console.log(__dirname)
    })
    globalShortcut.register('esc', () => {
      BrowserWindow.getFocusedWindow()?.hide()
    })



  console.log(__dirname)
  let tray = null;
  if(MAIN_WINDOW_VITE_DEV_SERVER_URL){
    tray = new Tray(nativeImage.createFromPath('./icon.png'))
  }else {
    tray = new Tray(nativeImage.createFromPath(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/assets/icon.png`)))
  }

      const contextMenu = Menu.buildFromTemplate([
        { label: '主程序', type: 'normal',click:()=>{BrowserWindow.fromId(mainID).show()} },
        { label: '设置', type: 'normal' ,click:()=>{BrowserWindow.fromId(settingID).show()}},
        { label: '退出', type: 'normal',click:()=>{app.quit()} },
      ])
      tray.setToolTip('This is my application.')
      tray.setContextMenu(contextMenu)
}).then(() => {
  createWindow();

  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
